package pemks.servlet;

import com.google.gson.JsonObject;
import jakarta.servlet.http.HttpServlet;
import pemks.dao.FileSecretDAO;
import pemks.dao.UserSecretDAO;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(
        name = "LocalServlet",
        urlPatterns = {"/local/save_kf", "/local/getuser_sk",
                       "/local/del_file", "/local/save_sk",
                       "/local/get_kf",},
        loadOnStartup = 1
)
public class LocalServlet extends HttpServlet {
    private FileSecretDAO fileSecretDAO = new FileSecretDAO();
    private UserSecretDAO userSecretDAO = new UserSecretDAO();

    @Override
    protected void doPost(jakarta.servlet.http.HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();
        JsonObject json = new JsonObject();

        try {
            switch (path) {
                case "/save_kf":
                    handleSaveKF(request, json);
                    break;
                case "/get_kf":
                    handleGetKF(request, json);
                    break;
                case "/getuser_sk":
                    handleGetSK(request, json);
                    break;
                case "/del_file":
                    handleDeleteFileSecret(request, json);
                    break;
                case "/save_sk":
                    handleSaveSK(request, json);
                    break;
                default:
                    sendError(response, 404, "Invalid endpoint");
            }
        } catch (Exception e) {
            sendError(response, 500, "Server error: " + e.getMessage());
        }

        response.getWriter().print(json.toString());
    }

    // 保存文件密钥
    private void handleSaveKF(HttpServletRequest request, JsonObject json) {
        int fileId = Integer.parseInt(request.getParameter("file_id"));
        String kf = request.getParameter("kf");
        String owner = request.getParameter("owner");

        if (fileSecretDAO.saveKF(fileId, kf, owner)) {
            json.addProperty("status", 200);
            json.addProperty("message", "success");
        } else {
            json.addProperty("status", 500);
            json.addProperty("message", "Failed to save key");
        }
    }

    // 获取用户私钥
    private void handleGetSK(HttpServletRequest request, JsonObject json) {
        String username = request.getParameter("username");
        String sk = userSecretDAO.getSK(username);

        if (sk != null) {
            json.addProperty("status", 200);
            json.addProperty("data", sk);
        } else {
            json.addProperty("status", 404);
            json.addProperty("message", "Secret key not found");
        }
    }

    private void handleGetKF(HttpServletRequest request, JsonObject json) {
        int fileId = Integer.parseInt(request.getParameter("file_id"));
        String kf = fileSecretDAO.getKF(fileId);

        if (kf != null) {
            json.addProperty("status", 200);
            json.addProperty("data", kf);
        } else {
            json.addProperty("status", 404);
            json.addProperty("message", "Secret key not found");
        }
    }

    // 删除文件密钥（级联删除）
    private void handleDeleteFileSecret(HttpServletRequest request, JsonObject json) {
        int fileId = Integer.parseInt(request.getParameter("delID"));

        if (fileSecretDAO.deleteKF(fileId)) {
            json.addProperty("status", 200);
            json.addProperty("message", "success");
        } else {
            json.addProperty("status", 500);
            json.addProperty("message", "Failed to delete key");
        }
    }

    // 保存用户私钥
    private void handleSaveSK(HttpServletRequest request, JsonObject json) {
        String username = request.getParameter("owner_name");
        String sk = request.getParameter("sk");

        if (userSecretDAO.saveSK(username, sk)) {
            json.addProperty("status", 200);
            json.addProperty("message", "success");
        } else {
            json.addProperty("status", 500);
            json.addProperty("message", "Failed to save secret key");
        }
    }

    private void sendError(HttpServletResponse response, int code, String msg)
            throws IOException {
        response.setStatus(code);
        JsonObject error = new JsonObject();
        error.addProperty("status", code);
        error.addProperty("message", msg);
        response.getWriter().print(error.toString());
    }
}